﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CurveInsert
{
    internal class CurveInfo
    {
        public string CurveID = "";
        public string ModelID = ""; //ps[0];  // C08
        public string TestTime = "";// $"{dt.Substring(0, 4)}-{dt.Substring(4, 2)}-{dt.Substring(6, 2)} {dt.Substring(8, 2)}:{dt.Substring(10, 2)}:{dt.Substring(12, 2)} ";
        public string Code = ""; // filename;  // 如 08_20190924163826_01_0050_299959
        public string PointCount = ""; //  ps[3]; // 27
        public string PointData = ""; // File.ReadAllText(curvefile); // 测量数据

        internal static CurveInfo Parse(string curvefile)
        {
            var filename = Path.GetFileNameWithoutExtension(curvefile);
            var ps = filename.Split('_');

            CurveInfo ci = new CurveInfo();

            try
            {

                // Kister: C08_20190924163826_01_0050_299959
                if (ps[0] == "08") // C08
                {
                    ci.ModelID = ps[0];  // C08
                    var dt = ps[1];
                    ci.TestTime = $"{dt.Substring(0, 4)}-{dt.Substring(4, 2)}-{dt.Substring(6, 2)} {dt.Substring(8, 2)}:{dt.Substring(10, 2)}:{dt.Substring(12, 2)} ";
                    ci.Code = filename;  // 如 08_20190924163826_01_0050_299959
                    ci.PointCount = ps[3];
                    ci.PointData = File.ReadAllText(curvefile);
                }
                // Cvinet: B_01_210623093757_000_1000014716.txt
                else if (ps[0].StartsWith("B"))
                {
                    ci.ModelID = ps[0];  // A=atlas, B=马头, C=CTL, D=蒂森NVH, E=蒂森检测台, F=霍塔NVH, G=霍塔检测台, H=kistler, I=SPH
                    var dt = ps[2];
                    ci.TestTime = $"20{dt.Substring(0, 2)}-{dt.Substring(2, 2)}-{dt.Substring(4, 2)} {dt.Substring(6, 2)}:{dt.Substring(8, 2)}:{dt.Substring(10, 2)} ";
                    ci.Code = filename;  // 如 B_01_210623093757_000_1000014716
                    ci.PointData = File.ReadAllText(curvefile);
                    ci.PointCount = ci.PointData.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Length.ToString();
                }
                else
                {
                    ci = null;
                }
            }
            catch
            {
                // 转换出错就返回null。
                ci = null;
            }

            return ci;
        }

        /// <summary>
        /// 返回Curve表的SQL插入字符串。
        /// </summary>
        /// <returns></returns>
        public string ToSqlString()
        { 
            return $"INSERT INTO Curves (ModelID, TestTime, Code, PointCount, PointData) VALUES('{ModelID}', '{TestTime}', '{Code}', {PointCount}, '{PointData}')"; 
        }
    }
}
